//商品列表
var app = getApp(); //全局APP

Page({
	//页面的初始数据
	data: {
		dorms: [],
		dormIds: [],
		buidingIndex: 0,
		operators: [],
		operatorIds: [],
		operatorIndex: 0,
		date: '',
		allNum: '发放总数:0套',
		num: '当日发放数:0套',
		listData: [],
		buttonDisabled: false // 按钮是否可用
	},

	//加载执行
	onShow: function() {
		this.getApartmentDormInfo();
		this.getApartmentOperatorsInfo();

		// 获取当前日期
		var today = new Date();
		today.setTime(today.getTime());
		var month = today.getMonth() + 1;
		var day = today.getDate();
		if (month < 10) month = "0" + month;
		if (day < 10) day = "0" + day;
		var time = today.getFullYear() + "-" + month + "-" + day;
		this.setData({
			date: time
		});
	},

	// 获取当前用户所在的宿舍楼
	getApartmentDormInfo: function() {
		var page = this;
		var data = {
			platform: 2 // 平台id，标识是小程序登录的 
		};

		// 提交请求
		app.api.getApartmentDormInfo(data, function(res) {
			if (res.status) {
				var tmp_dorms = [];
				var tmp_dormIds = [];
				for (var i = 0; i < res.data.length; i++) {
					tmp_dorms[i] = res.data[i].Dormname;
					tmp_dormIds[i] = res.data[i].id;
				}

				page.setData({
					dorms: tmp_dorms,
					dormIds: tmp_dormIds,
					buidingIndex: 0
				});
			} else {
				//报错了
				app.common.errorToBack(res.msg, 0);
			}
		});
	},

	// 获取当前用户信息
	getApartmentOperatorsInfo: function() {
		var page = this;
		var data = {
			platform: 2 // 平台id，标识是小程序登录的 
		};

		// 提交请求
		app.api.getApartmentOperatorsInfo(data, function(res) {
			if (res.status) {
				var tmp_operators = [];
				var tmp_operatorIds = [];
				tmp_operators[0] = res.data.truename;
				tmp_operatorIds[0] = res.data.mobile;

				page.setData({
					operators: tmp_operators,
					operatorIds: tmp_operatorIds,
					operatorIndex: 0
				});
			} else {
				//报错了
				app.common.errorToBack(res.msg, 0);
			}
		});
	},

	// 绑定宿舍楼
	bindDormChange: function(e) {
		this.setData({
			buidingIndex: e.detail.value
		});
	},

	// 绑定管理员
	bindOperatorChange: function(e) {
		this.setData({
			operatorIndex: e.detail.value
		});
	},

	// 绑定日期
	bindDateChange: function(e) {
		this.setData({
			date: e.detail.value
		});
	},

	// 查询
	sumbit: function() {
		var page = this;
		if (page.data.dormIds[page.data.buidingIndex] == '' &&
			page.data.operatorIds[page.data.operatorIndex] == '') {
			app.common.errorToBack('宿舍楼和管理员至少选择一项!', 0);
			return false;
		}

		app.common.buttonDisabled(this);
		
		var data = {
			dorm: page.data.dormIds[page.data.buidingIndex], // 宿舍楼
			operator: page.data.operatorIds[page.data.operatorIndex], // 管理员
			date: page.data.date, // 日期
			platform: 2 // 平台id，标识是小程序登录的 
		};

		// 提交请求
		app.api.getApartmentSuppliesInfo(data, function(res) {
			if (res.status) {
				page.setData({
					allNum: '总发放数:' + res.data.allNum + '套',
					num: '当日发放数:' + res.data.num + '套',
					listData: res.data.list
				});
			} else {
				//报错了
				app.common.errorToBack(res.msg, 0);

				page.setData({
					allNum: '总发放数:0套',
					num: '当日发放数:0套',
					listData: []
				});
			}
		});
	}
});
